package com.zfdang.touchhelper.tool;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import com.zfdang.touchhelper.MyApp;
import com.zfdang.touchhelper.bean.PackagePositionInfoBean;
import com.zfdang.touchhelper.bean.PackageWidgetInfoBean;
import com.zfdang.touchhelper.config.BaseConfig;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ly-dengpw
 */
public class SettingsTool {

    public static SettingsTool getInstance() {
        return SingletonFactory.INSTANCE;
    }

    private static class SingletonFactory {
        private static final SettingsTool INSTANCE = new SettingsTool();
    }

    private SettingsTool() {
        initSettings();
    }

    private void initSettings() {
    }


    /**
     * 获取APP白名单
     */
    public Set<String> getWhitelistPackages() {
        PackageManager packageManager = MyApp.getAppContext().getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        Set<String> pkgSystems = new HashSet<>();
        for (ResolveInfo info : resolveInfoList) {
            if ((info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                pkgSystems.add(info.activityInfo.packageName);
            }
        }
        return new HashSet<>(LyPreferenceTool.getInstance().getStringSet(BaseConfig.WHITELIST_PACKAGE, pkgSystems));
    }


    public List<String> getKeyWordList() {
        String text = LyPreferenceTool.getInstance().getString(BaseConfig.KEY_WORDS_LIST, "跳过");
        String[] keyWords = text.split(" ");
        return Arrays.asList(keyWords);
    }

    public String getKeyWordsAsString() {
        return LyPreferenceTool.getInstance().getString(BaseConfig.KEY_WORDS_LIST, "跳过");
    }


    public Map<String, Set<PackageWidgetInfoBean>> getPackageWidgets() {
        String json = LyPreferenceTool.getInstance().getString(BaseConfig.PACKAGE_WIDGETS, null);
        return GsonUtils.getPackageWidgeMaps(json);
    }

    public void setPackageWidgets(Map<String, Set<PackageWidgetInfoBean>> map) {
        String json = GsonUtils.toJson(map);
        LyPreferenceTool.getInstance().putString(BaseConfig.PACKAGE_WIDGETS, json);
    }


    public Map<String, PackagePositionInfoBean> getPackagePositions() {
        String json = LyPreferenceTool.getInstance().getString(BaseConfig.PACKAGE_POSITIONS, null);
        return GsonUtils.getPackagePositionMaps(json);
    }

    public void setPackagePositions(Map<String, PackagePositionInfoBean> map) {
        String json = GsonUtils.toJson(map);
        LyPreferenceTool.getInstance().putString(BaseConfig.PACKAGE_POSITIONS, json);
    }

}
